<template>
  <div class="key-detail-container">
    <el-container>
      <el-header class="header">
        <div class="header-left">
          <span class="logo">卡密管理系统</span>
        </div>
        <div class="header-right">
          <el-dropdown trigger="click">
            <span class="user-info">
              <User class="user-icon" />
              <span>管理员</span>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      <el-container>
        <el-aside width="200px" class="sidebar">
          <el-menu :default-openeds="['2']" router>
            <el-sub-menu index="1">
              <template #title>
                <DashboardIcon class="menu-icon" />
                <span>仪表盘</span>
              </template>
              <el-menu-item index="/dashboard">
                <span>数据统计</span>
              </el-menu-item>
            </el-sub-menu>
            <el-sub-menu index="2">
              <template #title>
                <Key class="menu-icon" />
                <span>卡密管理</span>
              </template>
              <el-menu-item index="/generate">
                <span>生成卡密</span>
              </el-menu-item>
              <el-menu-item index="/keys">
                <span>卡密列表</span>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>
        <el-main class="main-content">
          <el-card class="detail-card">
            <template #header>
              <div class="card-header">
                <el-button type="primary" size="small" @click="backToList" icon="ArrowLeft" />
                <span>卡密详情</span>
              </div>
            </template>
            <div class="loading-container" v-if="loading">
              <el-loading-spinner />
              <p>加载中...</p>
            </div>
            <div v-else class="key-detail-content">
              <el-descriptions title="卡密基本信息" :column="2" border>
                <el-descriptions-item label="卡密" :span="2">
                  <div class="key-value">{{ keyDetail.key }}</div>
                  <el-button type="primary" size="small" @click="copyKey" class="copy-btn">复制卡密</el-button>
                </el-descriptions-item>
                <el-descriptions-item label="所属应用">{{ keyDetail.app_name }}</el-descriptions-item>
                <el-descriptions-item label="卡类型">{{ getCardType(keyDetail.valid_days) }}</el-descriptions-item>
                <el-descriptions-item label="状态">
                  <el-tag :type="getStatusTagType(keyDetail.status)">{{ keyDetail.status_text }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="生成时间">{{ keyDetail.created_at }}</el-descriptions-item>
                <el-descriptions-item label="有效期至">{{ keyDetail.expires_at }}</el-descriptions-item>
                <el-descriptions-item label="激活时间" v-if="keyDetail.activation_time">{{ keyDetail.activation_time }}</el-descriptions-item>
                <el-descriptions-item label="未激活" v-else-if="keyDetail.status === 'unactivated'">{{ keyDetail.status_text }}</el-descriptions-item>
                <el-descriptions-item label="机器ID" v-if="keyDetail.machine_id">{{ keyDetail.machine_id }}</el-descriptions-item>
                <el-descriptions-item label="未绑定机器" v-else-if="keyDetail.status === 'activated'">{{ keyDetail.status_text }}</el-descriptions-item>
                <el-descriptions-item label="IP地址" v-if="keyDetail.machine_info && keyDetail.machine_info.ip_address">{{ keyDetail.machine_info.ip_address }}</el-descriptions-item>
                <el-descriptions-item label="IP归属地" v-if="keyDetail.machine_info && keyDetail.machine_info.ip_location">{{ keyDetail.machine_info.ip_location }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </el-card>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { User, DashboardIcon, Key } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const route = useRoute()
const keyDetail = ref({})
const loading = ref(true)

// 加载卡密详情
const loadKeyDetail = async () => {
  try {
    loading.value = true
    const keyId = route.params.id

    // 从localStorage获取token
    const token = localStorage.getItem('token')
    if (!token) {
      router.push('/login')
      return
    }

    // 调用后端API获取卡密详情
    const response = await axios.get(`/api/keys/${keyId}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    if (response.data.success) {
      keyDetail.value = response.data.data
    } else {
      ElMessage.error(response.data.message || '加载卡密详情失败')
      keyDetail.value = {}
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
    console.error('Failed to load key detail:', error)
    keyDetail.value = {}
  } finally {
    loading.value = false
  }
}

// 获取卡类型
const getCardType = (validDays) => {
  if (validDays === 0) return '永久卡'
  if (validDays === 1) return '日卡'
  if (validDays === 7) return '周卡'
  if (validDays === 30) return '月卡'
  if (validDays === 90) return '季卡'
  if (validDays === 180) return '半年卡'
  if (validDays === 365) return '年卡'
  return '自定义'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 'activated':
      return 'success'
    case 'unactivated':
      return 'warning'
    case 'expired':
      return 'danger'
    default:
      return 'default'
  }
}

// 复制卡密
const copyKey = () => {
  navigator.clipboard.writeText(keyDetail.value.key)
    .then(() => {
      ElMessage.success('卡密已复制到剪贴板')
    })
    .catch(err => {
      ElMessage.error('复制失败，请手动复制')
      console.error('Failed to copy:', err)
    })
}

// 返回卡密列表
const backToList = () => {
  router.push('/keys')
}

// 退出登录
const handleLogout = () => {
  localStorage.removeItem('token')
  ElMessage.success('退出成功')
  router.push('/login')
}

onMounted(() => {
  loadKeyDetail()
})
</script>

<style scoped>
.key-detail-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.header {
  background-color: #409eff;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
}
.logo {
  font-size: 20px;
  font-weight: bold;
}
.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}
.user-icon {
  margin-right: 5px;
}
.sidebar {
  background-color: #f0f2f5;
  padding-top: 20px;
}
.menu-icon {
  margin-right: 10px;
}
.main-content {
  padding: 20px;
  background-color: #f5f7fa;
  overflow-y: auto;
  flex: 1;
}
.detail-card {
  margin-bottom: 20px;
}
.card-header {
  font-size: 16px;
  font-weight: bold;
  display: flex;
  align-items: center;
}
.card-header .el-button {
  margin-right: 15px;
}
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
}
.key-detail-content {
  padding: 20px 0;
}
.key-value {
  font-size: 18px;
  font-weight: bold;
  letter-spacing: 2px;
  margin-bottom: 10px;
}
.copy-btn {
  margin-left: 10px;
}
</style>